<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽">
    </el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存修改</el-button>
    <el-button type="danger" @click="batchDel">批量删除</el-button>
    <el-tree
      :data="data"
      :props="defaultProps"
      show-checkbox
      node-key="catId"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
       <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
<!--          如果层级小于等于2 说明是上级不是最后一级 只能在此追加-->
          <el-button
            v-if="node.level <=2"
            type="text"
            size="mini"
            @click="() => append(data)">
            Append
          </el-button>
          <!--          数组的长度==0 说明是最后一级 只能删除-->
          <el-button
            v-if="node.childNodes.length==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            Delete
          </el-button>
           <el-button

             type="text"
             size="mini"
             @click="() => edit(node, data)">
            edit
          </el-button>
        </span>
      </span>

    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="分类计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateCategory()">确 定</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import log from "../sys/log";

export default {
// import 引入的组件需要要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      draggable: false,
      data: [],
      pCid: [],
      title: "",
      updateNodes: [],
      maxLevel: 0,
      category: {
        catId: null,
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: ""
      },
      expandedKey: [],
      dialogVisible: false,
      dialogType: "",
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    };
  },
//  计算属性
  computed: {},
//  监控data中的数据变化
  watch: {},
//  方法集合
  methods: {
    batchDel() {
      let catIds = []
      let catNames=[]
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId)
        catNames.push(checkedNodes[i].name)
      }
      //弹框
      this.$confirm(`是否批量删除${catNames}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //请求
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(catIds, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("删除成功")
          } else {
            console.log("删除失败")
          }
        });
        //弹提示
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        //删除成功之后,重新加载tree
        this.getMenus()
        //需要将上次的节点展开
        this.expandedKey = [node.parent.data.catId]
      }).catch(() => {

        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    allowDrop(draggingNode, dropNode, type) {
      //1、被拖动的当前节点以及所在的父节点总层数不能大于3

      //1）、被拖动的当前节点总层数
      console.log("allowDrop:", draggingNode, dropNode, type);
      //
      this.countNodeLevel(draggingNode);
      //当前正在拖动的节点+父节点所在的深度不大于3即可
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;

      if (type == "inner") {
        //分几种情况
        //1.同级=>下级
        //2.同级=>上级


        return (deep + dropNode.level) <= 3;
      } else {


        return (deep + dropNode.parent.level) <= 3;
      }
    },
    countNodeLevel(node) {
      //找到所有子节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    batchSave() {
      this.$http({
        url: this.$http.adornUrl(`/product/category/update/sort`),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          //弹提示
          this.$message({
            type: 'success',
            message: '更新节点信息 成功!'
          });
          //刷新菜单
          this.getMenus()
          //打开要默认展开的菜单
          this.expandedKey = this.pCid
          this.updateNodes = []
          this.maxLevel = 0
          this.pCid = 0
        } else {
          //弹提示
          this.$message({
            type: 'error',
            message: '更新节点信息 失败'
          });
        }
      });
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("handleDrop: ", draggingNode, dropNode, dropType);
      //1、当前节点最新的父节点id
      let pCid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);


      //2、当前拖拽节点的最新顺序，
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //如果遍历的是当前正在拖拽的节点
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            //当前节点的层级发生变化
            catLevel = siblings[i].level;
            //修改他子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel
          });
        } else {
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i});
        }
      }

      //3、当前拖拽节点的最新层级
      // console.log("updateNodes", this.updateNodes);


    },
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    saveOrUpdateCategory() {
      console.log(this.category)
      if (this.dialogType == "add") {
        //新增
        console.log("新增")
        this.saveCategory()
      } else {
        //修改
        console.log("修改")
        this.updateCategory()
      }

    },
    saveCategory() {
      //发请求
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log("saveCategory成功")
          //弹提示
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
          //关闭对话框
          this.dialogVisible = false
          //刷新树
          this.getMenus()
          //默认要展开的菜单
          console.log(this.category.parentCid)
          this.expandedKey = [this.category.parentCid]
          console.log(this.expandedKey)
        } else {
          console.log("saveCategory失败")
          //弹提示
          this.$message({
            type: 'error',
            message: '保存失败'
          });
        }
      });
    },
    getMenus() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.data = data.data
        } else {
          this.data = []
        }
        this.dataListLoading = false
      })
    },
    append(data) {
      console.log("append" + data)
      this.dialogVisible = true
      this.dialogType = "add"
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1

      //添加时的默认值
      //todo 这里应该有优化写法
      this.category.catId = null
      this.category.icon = null
      this.category.productUnit = null
      this.category.sort = 0
      this.category.showStatus = 1
      this.category.name = null

      this.title = "添加"
    },
    edit(node, data) {
      this.dialogVisible = true
      this.dialogType = "edit"

      this.title = "修改"
      //发送请求 获取当前最新的并赋值
      this.getCategoryById(data.catId)
    },
    remove(node, data) {
      let ids = [data.catId]
      //弹框
      this.$confirm(`此操作将永久删除${data.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //请求
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("删除成功")
          } else {
            console.log("删除失败")
          }
        });
        //弹提示
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        //删除成功之后,重新加载tree
        this.getMenus()
        //需要将上次的节点展开
        this.expandedKey = [node.parent.data.catId]
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })


    },
    updateCategory() {
      //只能发一些需要修改的
      let {catId, name, icon, productUnit} = this.category
      //发请求
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData({catId, name, icon, productUnit}, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log("updateCategory 成功")
          //弹提示
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
          //关闭对话框
          this.dialogVisible = false
          //刷新树
          this.getMenus()
          //默认要展开的菜单
          console.log(this.category.parentCid)
          this.expandedKey = [this.category.parentCid]
          console.log(this.expandedKey)
        } else {
          console.log("updateCategory 失败")
          //弹提示
          this.$message({
            type: 'error',
            message: '保存失败'
          });
        }
      });
    },
    getCategoryById(catId) {
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${catId}`),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log('请求成功', data)
          this.category.name = data.data.name
          this.category.catId = data.data.catId
          this.category.icon = data.data.icon
          this.category.productUnit = data.data.productUnit
          this.category.parentCid = data.data.parentCid

        } else {
          console.log('请求失败')
        }
      })
    }
  },
// 生命周期-创建完成(可以访问当前this实例)
  created() {
    this.getMenus();
  },
// 改在完成,可以方位dom元素
  mounted() {
  },
  beforeCreate() {
  },// 创建之前
  beforeMount() {
  },// 挂载之前
  beforeDestroy() {
  },
  destroyed() {
  },
  activated() {
  }
};
</script>

<style scoped>

</style>
